package org.spring.springboot.service.impl;

import org.spring.springboot.dao.UserMenuDao;
import org.spring.springboot.domain.AdminUserMenu;
import org.spring.springboot.service.UserMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 城市业务逻辑实现类
 *
 * Created by 赵新国 on 07/02/2017.
 */
@Service
public class UserMenuServiceImpl implements UserMenuService {

    @Autowired
    private UserMenuDao userMenuDao;

    /**
     * 获取用户拥有菜单id的集合
     *
     * @param userId
     * @return
     */
    @Override
    public List<Short> getUserMenuIds(Short userId) {
        return userMenuDao.getMenuIdsByUserId(userId);
    }

    /**
     * 给用户授权菜单权限
     *
     * @param userId
     * @param newList
     */
    @Override
    public void saveUserMenu(Short userId, List<Short> newList) {
        if (StringUtils.isEmpty(newList)) {
            throw new RuntimeException("请先选择资源权限");
        }
        List<Short> oldList = getUserMenuIds(userId);
        //是否删除
        if (!StringUtils.isEmpty(oldList)) {
            for (int i = 0, j = oldList.size(); i < j; i++) {
                if (!newList.contains(oldList.get(i))) {
                    userMenuDao.deleteUserMenu(userId, oldList.get(i));
                }
            }
        }

        //是否添加
        for (int i = 0, j = newList.size(); i < j; i++) {
            if (!oldList.contains(newList.get(i))) {
                userMenuDao.insertSelective(new AdminUserMenu(userId, newList.get(i)));
            }
        }
    }
}